using AuthService.Application.Services;
using AuthService.Domain.Enums;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.Net;
using System.Text.Json;
using HttpMethod = AuthService.Domain.Enums.HttpMethod;

namespace AuthService.Application.Middleware;

/// <summary>
/// 动态路由中间件
/// 根据配置的动态API端点进行请求路由和转发
/// </summary>
public class DynamicRoutingMiddleware
{
    private readonly RequestDelegate _next;
    private readonly IServiceProvider _serviceProvider;
    private readonly IHttpClientFactory _httpClientFactory;
    private readonly ILogger<DynamicRoutingMiddleware> _logger;

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="next">下一个中间件</param>
    /// <param name="serviceProvider">服务提供者</param>
    /// <param name="httpClientFactory">HTTP客户端工厂</param>
    /// <param name="logger">日志记录器</param>
    public DynamicRoutingMiddleware(
        RequestDelegate next,
        IServiceProvider serviceProvider,
        IHttpClientFactory httpClientFactory,
        ILogger<DynamicRoutingMiddleware> logger)
    {
        _next = next;
        _serviceProvider = serviceProvider;
        _httpClientFactory = httpClientFactory;
        _logger = logger;
    }

    /// <summary>
    /// 中间件执行方法
    /// </summary>
    /// <param name="context">HTTP上下文</param>
    /// <returns>任务</returns>
    public async Task InvokeAsync(HttpContext context)
    {
        try
        {
            // 创建作用域来获取作用域服务
            using var scope = _serviceProvider.CreateScope();
            var dynamicApiService = scope.ServiceProvider.GetRequiredService<IDynamicApiService>();

            // 获取请求信息
            var requestPath = context.Request.Path.Value ?? "/";
            var methodString = context.Request.Method;
            var tenantId = GetTenantId(context);

            // 解析HTTP方法
            if (!Enum.TryParse<HttpMethod>(methodString, true, out var httpMethod))
            {
                _logger.LogWarning("不支持的HTTP方法: {Method}", methodString);
                await _next(context);
                return;
            }

            // 查找匹配的API端点
            var endpoint = await dynamicApiService.FindMatchingEndpointAsync(requestPath, httpMethod, tenantId);
            if (endpoint == null)
            {
                // 没有匹配的动态端点，继续执行下一个中间件
                await _next(context);
                return;
            }

            // 检查端点是否启用
            if (!endpoint.IsEnabled)
            {
                _logger.LogWarning("API端点已禁用: {EndpointName}", endpoint.Name);
                context.Response.StatusCode = (int)HttpStatusCode.NotFound;
                await context.Response.WriteAsync("API endpoint is disabled");
                return;
            }

            // 检查认证和授权
            if (!await CheckAuthorizationAsync(context, endpoint))
            {
                return; // 认证失败，已设置响应
            }

            // 检查限流
            if (!await CheckRateLimitAsync(context, endpoint))
            {
                return; // 限流触发，已设置响应
            }

            // 记录访问（在后台任务中创建新的作用域）
            var endpointId = endpoint.Id;
            _ = Task.Run(async () =>
            {
                try
                {
                    using var backgroundScope = _serviceProvider.CreateScope();
                    var backgroundDynamicApiService = backgroundScope.ServiceProvider.GetRequiredService<IDynamicApiService>();
                    await backgroundDynamicApiService.RecordAccessAsync(endpointId);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "记录API访问失败: {EndpointId}", endpointId);
                }
            });

            // 处理请求（内部服务调用或外部转发）
            await ProcessRequestAsync(context, endpoint);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "动态路由中间件执行失败");
            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            await context.Response.WriteAsync("Internal server error");
        }
    }

    /// <summary>
    /// 获取租户ID
    /// </summary>
    /// <param name="context">HTTP上下文</param>
    /// <returns>租户ID</returns>
    private string? GetTenantId(HttpContext context)
    {
        // 从请求头获取租户ID
        if (context.Request.Headers.TryGetValue("X-Tenant-Id", out var tenantHeader))
        {
            return tenantHeader.FirstOrDefault();
        }

        // 从查询参数获取租户ID
        if (context.Request.Query.TryGetValue("tenantId", out var tenantQuery))
        {
            return tenantQuery.FirstOrDefault();
        }

        // 从用户声明获取租户ID
        var tenantClaim = context.User?.FindFirst("tenant_id");
        return tenantClaim?.Value;
    }

    /// <summary>
    /// 检查认证和授权
    /// </summary>
    /// <param name="context">HTTP上下文</param>
    /// <param name="endpoint">API端点</param>
    /// <returns>是否通过检查</returns>
    private async Task<bool> CheckAuthorizationAsync(HttpContext context, Domain.Entities.DynamicApiEndpoint endpoint)
    {
        // 如果不需要认证，直接通过
        if (!endpoint.RequireAuthentication)
        {
            return true;
        }

        // 检查用户是否已认证
        if (!context.User.Identity?.IsAuthenticated ?? true)
        {
            _logger.LogWarning("用户未认证，访问端点: {EndpointName}", endpoint.Name);
            context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
            await context.Response.WriteAsync("Unauthorized");
            return false;
        }

        // 获取用户角色和权限
        var userRoles = context.User.FindAll("role").Select(c => c.Value);
        var userPermissions = context.User.FindAll("permission").Select(c => c.Value);

        // 检查访问权限
        if (!endpoint.CheckAccess(userRoles, userPermissions))
        {
            _logger.LogWarning("用户权限不足，访问端点: {EndpointName}, 用户: {UserId}",
                endpoint.Name, context.User.FindFirst("sub")?.Value);
            context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
            await context.Response.WriteAsync("Forbidden");
            return false;
        }

        return true;
    }

    /// <summary>
    /// 检查限流
    /// </summary>
    /// <param name="context">HTTP上下文</param>
    /// <param name="endpoint">API端点</param>
    /// <returns>是否通过检查</returns>
    private async Task<bool> CheckRateLimitAsync(HttpContext context, Domain.Entities.DynamicApiEndpoint endpoint)
    {
        // 如果没有配置限流，直接通过
        if (!endpoint.RateLimitPerMinute.HasValue || endpoint.RateLimitPerMinute.Value <= 0)
        {
            return true;
        }

        // TODO: 实现限流逻辑
        // 这里可以集成Redis或内存缓存来实现限流
        // 暂时返回true，后续可以扩展

        return true;
    }

    /// <summary>
    /// 处理请求（内部服务调用或外部转发）
    /// </summary>
    /// <param name="context">HTTP上下文</param>
    /// <param name="endpoint">API端点</param>
    /// <returns>任务</returns>
    private async Task ProcessRequestAsync(HttpContext context, Domain.Entities.DynamicApiEndpoint endpoint)
    {
        // 如果是内部服务调用（TargetUrl为空且TargetService不为空）
        if (string.IsNullOrEmpty(endpoint.TargetUrl) && !string.IsNullOrEmpty(endpoint.TargetService))
        {
            await HandleInternalServiceCallAsync(context, endpoint);
        }
        else
        {
            // 外部服务转发
            await ForwardRequestAsync(context, endpoint);
        }
    }

    /// <summary>
    /// 处理内部服务调用
    /// </summary>
    /// <param name="context">HTTP上下文</param>
    /// <param name="endpoint">API端点</param>
    /// <returns>任务</returns>
    private async Task HandleInternalServiceCallAsync(HttpContext context, Domain.Entities.DynamicApiEndpoint endpoint)
    {
        try
        {
            // 根据服务名称调用对应的服务方法
            if (endpoint.TargetService == "IUserService")
            {
                await HandleUserServiceCallAsync(context, endpoint);
            }
            else if (endpoint.TargetService == "ITestService")
            {
                await HandleTestServiceCallAsync(context, endpoint);
            }
            else
            {
                _logger.LogError("不支持的内部服务: {ServiceName}", endpoint.TargetService);
                context.Response.StatusCode = (int)HttpStatusCode.NotImplemented;
                await context.Response.WriteAsync($"Internal service not supported: {endpoint.TargetService}");
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "内部服务调用失败: {ServiceName}.{EndpointName}",
                endpoint.TargetService, endpoint.Name);
            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            await context.Response.WriteAsync("Internal service call failed");
        }
    }

    /// <summary>
    /// 处理用户服务调用
    /// </summary>
    /// <param name="context">HTTP上下文</param>
    /// <param name="endpoint">API端点</param>
    /// <returns>任务</returns>
    private async Task HandleUserServiceCallAsync(HttpContext context, Domain.Entities.DynamicApiEndpoint endpoint)
    {
        using var scope = _serviceProvider.CreateScope();
        var userService = scope.ServiceProvider.GetRequiredService<IUserServiceSimplified>();

        // 根据端点名称调用对应的方法
        var methodName = endpoint.Name.Split('.').LastOrDefault();

        switch (methodName)
        {
            case "GetUsersAsync":
                await HandleGetUsersAsync(context, userService);
                break;
            case "GetUserByIdAsync":
                await HandleGetUserByIdAsync(context, userService, endpoint);
                break;
            case "GetUserByUsernameAsync":
                await HandleGetUserByUsernameAsync(context, userService);
                break;
            case "GetUserByEmailAsync":
                await HandleGetUserByEmailAsync(context, userService);
                break;
            case "CreateUserAsync":
                await HandleCreateUserAsync(context, userService);
                break;
            case "UpdateUserAsync":
                await HandleUpdateUserAsync(context, userService, endpoint);
                break;
            case "DeleteUserAsync":
                await HandleDeleteUserAsync(context, userService, endpoint);
                break;
            case "GetUserStatisticsAsync":
                await HandleGetUserStatisticsAsync(context, userService);
                break;
            default:
                _logger.LogError("不支持的用户服务方法: {MethodName}", methodName);
                context.Response.StatusCode = (int)HttpStatusCode.NotImplemented;
                await context.Response.WriteAsync($"Method not supported: {methodName}");
                break;
        }
    }

    /// <summary>
    /// 转发请求到目标服务
    /// </summary>
    /// <param name="context">HTTP上下文</param>
    /// <param name="endpoint">API端点</param>
    /// <returns>任务</returns>
    private async Task ForwardRequestAsync(HttpContext context, Domain.Entities.DynamicApiEndpoint endpoint)
    {
        try
        {
            // 构建目标URL
            var targetUrl = BuildTargetUrl(context, endpoint);
            if (string.IsNullOrEmpty(targetUrl))
            {
                _logger.LogError("无法构建目标URL，端点: {EndpointName}", endpoint.Name);
                context.Response.StatusCode = (int)HttpStatusCode.BadGateway;
                await context.Response.WriteAsync("Bad gateway");
                return;
            }

            // 创建HTTP客户端
            using var httpClient = _httpClientFactory.CreateClient();
            httpClient.Timeout = TimeSpan.FromSeconds(endpoint.TimeoutSeconds);

            // 创建请求消息
            var requestMessage = await CreateRequestMessageAsync(context, targetUrl, endpoint);

            // 发送请求
            var response = await httpClient.SendAsync(requestMessage, context.RequestAborted);

            // 复制响应
            await CopyResponseAsync(response, context);
        }
        catch (TaskCanceledException ex) when (ex.InnerException is TimeoutException)
        {
            _logger.LogWarning("请求超时，端点: {EndpointName}, 超时时间: {Timeout}秒",
                endpoint.Name, endpoint.TimeoutSeconds);
            context.Response.StatusCode = (int)HttpStatusCode.RequestTimeout;
            await context.Response.WriteAsync("Request timeout");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "转发请求失败，端点: {EndpointName}", endpoint.Name);
            context.Response.StatusCode = (int)HttpStatusCode.BadGateway;
            await context.Response.WriteAsync("Bad gateway");
        }
    }

    /// <summary>
    /// 构建目标URL
    /// </summary>
    /// <param name="context">HTTP上下文</param>
    /// <param name="endpoint">API端点</param>
    /// <returns>目标URL</returns>
    private string? BuildTargetUrl(HttpContext context, Domain.Entities.DynamicApiEndpoint endpoint)
    {
        var baseUrl = endpoint.TargetUrl;

        // 如果没有配置目标URL，尝试通过服务发现
        if (string.IsNullOrEmpty(baseUrl) && !string.IsNullOrEmpty(endpoint.TargetService))
        {
            // TODO: 集成Consul服务发现
            // 暂时返回null，后续实现服务发现逻辑
            _logger.LogWarning("服务发现功能尚未实现，服务名: {ServiceName}", endpoint.TargetService);
            return null;
        }

        if (string.IsNullOrEmpty(baseUrl))
        {
            return null;
        }

        // 移除末尾的斜杠
        baseUrl = baseUrl.TrimEnd('/');

        // 获取请求路径和查询字符串
        var requestPath = context.Request.Path.Value ?? "";
        var queryString = context.Request.QueryString.Value ?? "";

        // 构建完整URL
        return $"{baseUrl}{requestPath}{queryString}";
    }

    /// <summary>
    /// 创建请求消息
    /// </summary>
    /// <param name="context">HTTP上下文</param>
    /// <param name="targetUrl">目标URL</param>
    /// <param name="endpoint">API端点</param>
    /// <returns>请求消息</returns>
    private async Task<HttpRequestMessage> CreateRequestMessageAsync(HttpContext context, string targetUrl, Domain.Entities.DynamicApiEndpoint endpoint)
    {
        var request = new HttpRequestMessage
        {
            Method = new System.Net.Http.HttpMethod(context.Request.Method),
            RequestUri = new Uri(targetUrl)
        };

        // 复制请求头
        foreach (var header in context.Request.Headers)
        {
            // 跳过一些不应该转发的头
            if (ShouldSkipHeader(header.Key))
                continue;

            if (!request.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray()))
            {
                request.Content?.Headers.TryAddWithoutValidation(header.Key, header.Value.ToArray());
            }
        }

        // 添加自定义头
        foreach (var header in endpoint.Headers)
        {
            request.Headers.TryAddWithoutValidation(header.Key, header.Value);
        }

        // 复制请求体
        if (context.Request.ContentLength > 0)
        {
            var content = new StreamContent(context.Request.Body);
            if (!string.IsNullOrEmpty(context.Request.ContentType))
            {
                content.Headers.TryAddWithoutValidation("Content-Type", context.Request.ContentType);
            }
            request.Content = content;
        }

        return request;
    }

    /// <summary>
    /// 检查是否应该跳过某个请求头
    /// </summary>
    /// <param name="headerName">请求头名称</param>
    /// <returns>是否跳过</returns>
    private bool ShouldSkipHeader(string headerName)
    {
        var skipHeaders = new[]
        {
            "Host", "Connection", "Transfer-Encoding", "Upgrade",
            "Proxy-Connection", "Proxy-Authenticate", "Proxy-Authorization"
        };

        return skipHeaders.Contains(headerName, StringComparer.OrdinalIgnoreCase);
    }

    /// <summary>
    /// 复制响应到原始上下文
    /// </summary>
    /// <param name="response">HTTP响应</param>
    /// <param name="context">HTTP上下文</param>
    /// <returns>任务</returns>
    private async Task CopyResponseAsync(HttpResponseMessage response, HttpContext context)
    {
        // 设置状态码
        context.Response.StatusCode = (int)response.StatusCode;

        // 复制响应头
        foreach (var header in response.Headers)
        {
            context.Response.Headers[header.Key] = header.Value.ToArray();
        }

        foreach (var header in response.Content.Headers)
        {
            context.Response.Headers[header.Key] = header.Value.ToArray();
        }

        // 复制响应体
        await response.Content.CopyToAsync(context.Response.Body);
    }

    /// <summary>
    /// 处理获取用户列表请求
    /// </summary>
    private async Task HandleGetUsersAsync(HttpContext context, IUserServiceSimplified userService)
    {
        try
        {
            // 解析查询参数
            var query = context.Request.Query;
            var pageNumber = int.TryParse(query["pageNumber"], out var pn) ? pn : 1;
            var pageSize = int.TryParse(query["pageSize"], out var ps) ? ps : 10;
            var tenantId = query["tenantId"].ToString();

            // 调用服务方法
            var result = await userService.GetUsersAsync(pageNumber, pageSize, tenantId);

            // 返回JSON响应
            context.Response.ContentType = "application/json";
            await context.Response.WriteAsync(JsonSerializer.Serialize(new
            {
                users = result.Users,
                totalCount = result.TotalCount,
                pageNumber,
                pageSize
            }, new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                WriteIndented = true
            }));
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "处理GetUsersAsync请求失败");
            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            await context.Response.WriteAsync("Failed to get users");
        }
    }

    /// <summary>
    /// 处理根据ID获取用户请求
    /// </summary>
    private async Task HandleGetUserByIdAsync(HttpContext context, IUserServiceSimplified userService, Domain.Entities.DynamicApiEndpoint endpoint)
    {
        try
        {
            // 从路由参数中获取ID
            using var scope = _serviceProvider.CreateScope();
            var dynamicApiService = scope.ServiceProvider.GetRequiredService<IDynamicApiService>();
            var (isMatch, parameters) = dynamicApiService.MatchPath(context.Request.Path, endpoint.PathTemplate);
            if (!isMatch || !parameters.TryGetValue("id", out var idStr) || !Guid.TryParse(idStr, out var id))
            {
                context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                await context.Response.WriteAsync("Invalid user ID");
                return;
            }

            // 调用服务方法
            var user = await userService.GetUserByIdAsync(id);
            if (user == null)
            {
                context.Response.StatusCode = (int)HttpStatusCode.NotFound;
                await context.Response.WriteAsync("User not found");
                return;
            }

            // 返回JSON响应
            context.Response.ContentType = "application/json";
            await context.Response.WriteAsync(JsonSerializer.Serialize(user, new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                WriteIndented = true
            }));
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "处理GetUserByIdAsync请求失败");
            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            await context.Response.WriteAsync("Failed to get user");
        }
    }

    /// <summary>
    /// 处理根据用户名获取用户请求
    /// </summary>
    private async Task HandleGetUserByUsernameAsync(HttpContext context, IUserServiceSimplified userService)
    {
        try
        {
            var username = context.Request.Query["username"].ToString();
            if (string.IsNullOrEmpty(username))
            {
                context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                await context.Response.WriteAsync("Username is required");
                return;
            }

            var user = await userService.GetUserByUsernameAsync(username);
            if (user == null)
            {
                context.Response.StatusCode = (int)HttpStatusCode.NotFound;
                await context.Response.WriteAsync("User not found");
                return;
            }

            context.Response.ContentType = "application/json";
            await context.Response.WriteAsync(JsonSerializer.Serialize(user, new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                WriteIndented = true
            }));
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "处理GetUserByUsernameAsync请求失败");
            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            await context.Response.WriteAsync("Failed to get user");
        }
    }

    /// <summary>
    /// 处理根据邮箱获取用户请求
    /// </summary>
    private async Task HandleGetUserByEmailAsync(HttpContext context, IUserServiceSimplified userService)
    {
        try
        {
            var email = context.Request.Query["email"].ToString();
            if (string.IsNullOrEmpty(email))
            {
                context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                await context.Response.WriteAsync("Email is required");
                return;
            }

            var user = await userService.GetUserByEmailAsync(email);
            if (user == null)
            {
                context.Response.StatusCode = (int)HttpStatusCode.NotFound;
                await context.Response.WriteAsync("User not found");
                return;
            }

            context.Response.ContentType = "application/json";
            await context.Response.WriteAsync(JsonSerializer.Serialize(user, new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                WriteIndented = true
            }));
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "处理GetUserByEmailAsync请求失败");
            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            await context.Response.WriteAsync("Failed to get user");
        }
    }

    /// <summary>
    /// 处理获取用户统计请求
    /// </summary>
    private async Task HandleGetUserStatisticsAsync(HttpContext context, IUserServiceSimplified userService)
    {
        try
        {
            // 简化版本：返回基础统计信息
            var (users, totalCount) = await userService.GetUsersAsync();
            var statistics = new
            {
                TotalUsers = totalCount,
                ActiveUsers = totalCount,
                InactiveUsers = 0,
                LockedUsers = 0
            };

            context.Response.ContentType = "application/json";
            await context.Response.WriteAsync(JsonSerializer.Serialize(statistics, new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                WriteIndented = true
            }));
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "处理GetUserStatisticsAsync请求失败");
            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            await context.Response.WriteAsync("Failed to get user statistics");
        }
    }

    /// <summary>
    /// 处理创建用户请求
    /// </summary>
    private async Task HandleCreateUserAsync(HttpContext context, IUserServiceSimplified userService)
    {
        try
        {
            // 读取请求体
            using var reader = new StreamReader(context.Request.Body);
            var requestBody = await reader.ReadToEndAsync();

            if (string.IsNullOrWhiteSpace(requestBody))
            {
                context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                await context.Response.WriteAsync("请求体不能为空");
                return;
            }

            // 解析JSON
            var createRequest = JsonSerializer.Deserialize<CreateUserRequest>(requestBody, new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true
            });

            if (createRequest == null)
            {
                context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                await context.Response.WriteAsync("无效的请求格式");
                return;
            }

            // 验证必填字段
            if (string.IsNullOrWhiteSpace(createRequest.Username) ||
                string.IsNullOrWhiteSpace(createRequest.Email) ||
                string.IsNullOrWhiteSpace(createRequest.Password))
            {
                context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                await context.Response.WriteAsync("用户名、邮箱和密码不能为空");
                return;
            }

            // 创建用户
            var user = await userService.CreateUserAsync(
                createRequest.Username,
                createRequest.Email,
                createRequest.Password,
                createRequest.DisplayName);

            // 返回成功响应（不包含敏感信息）
            var response = new
            {
                Id = user.Id,
                Username = user.Username,
                Email = user.Email,
                DisplayName = user.DisplayName,
                CreatedAt = user.CreatedAt
            };

            context.Response.ContentType = "application/json";
            await context.Response.WriteAsync(JsonSerializer.Serialize(response, new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            }));
        }
        catch (InvalidOperationException ex)
        {
            context.Response.StatusCode = (int)HttpStatusCode.Conflict;
            await context.Response.WriteAsync(ex.Message);
        }
        catch (Exception ex)
        {
            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            await context.Response.WriteAsync($"创建用户失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 创建用户请求模型
    /// </summary>
    public class CreateUserRequest
    {
        public string Username { get; set; } = string.Empty;
        public string Email { get; set; } = string.Empty;
        public string Password { get; set; } = string.Empty;
        public string? DisplayName { get; set; }
    }

    /// <summary>
    /// 处理更新用户请求
    /// </summary>
    private async Task HandleUpdateUserAsync(HttpContext context, IUserServiceSimplified userService, Domain.Entities.DynamicApiEndpoint endpoint)
    {
        context.Response.StatusCode = (int)HttpStatusCode.NotImplemented;
        await context.Response.WriteAsync("UpdateUserAsync not implemented yet");
    }

    /// <summary>
    /// 处理删除用户请求
    /// </summary>
    private async Task HandleDeleteUserAsync(HttpContext context, IUserServiceSimplified userService, Domain.Entities.DynamicApiEndpoint endpoint)
    {
        context.Response.StatusCode = (int)HttpStatusCode.NotImplemented;
        await context.Response.WriteAsync("DeleteUserAsync not implemented yet");
    }

    /// <summary>
    /// 处理测试服务调用
    /// </summary>
    /// <param name="context">HTTP上下文</param>
    /// <param name="endpoint">API端点</param>
    /// <returns>任务</returns>
    private async Task HandleTestServiceCallAsync(HttpContext context, Domain.Entities.DynamicApiEndpoint endpoint)
    {
        using var scope = _serviceProvider.CreateScope();
        var testService = scope.ServiceProvider.GetRequiredService<ITestService>();

        // 根据端点名称调用对应的方法
        var methodName = endpoint.Name.Split('.').LastOrDefault();

        switch (methodName)
        {
            case "GetMessageAsync":
                await HandleGetMessageAsync(context, testService);
                break;
            case "GetTestDataAsync":
                await HandleGetTestDataAsync(context, testService, endpoint);
                break;
            case "CreateTestDataAsync":
                await HandleCreateTestDataAsync(context, testService);
                break;
            case "GetAllTestDataAsync":
                await HandleGetAllTestDataAsync(context, testService);
                break;
            default:
                _logger.LogError("不支持的测试服务方法: {MethodName}", methodName);
                context.Response.StatusCode = (int)HttpStatusCode.NotImplemented;
                await context.Response.WriteAsync($"Method not supported: {methodName}");
                break;
        }
    }

    /// <summary>
    /// 处理获取测试消息请求
    /// </summary>
    private async Task HandleGetMessageAsync(HttpContext context, ITestService testService)
    {
        try
        {
            var message = await testService.GetMessageAsync();

            context.Response.ContentType = "application/json";
            await context.Response.WriteAsync(JsonSerializer.Serialize(new
            {
                message,
                timestamp = DateTime.UtcNow
            }, new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                WriteIndented = true
            }));
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "处理GetMessageAsync请求失败");
            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            await context.Response.WriteAsync("Failed to get message");
        }
    }

    /// <summary>
    /// 处理根据ID获取测试数据请求
    /// </summary>
    private async Task HandleGetTestDataAsync(HttpContext context, ITestService testService, Domain.Entities.DynamicApiEndpoint endpoint)
    {
        try
        {
            // 从路由参数中获取ID
            using var scope = _serviceProvider.CreateScope();
            var dynamicApiService = scope.ServiceProvider.GetRequiredService<IDynamicApiService>();
            var (isMatch, parameters) = dynamicApiService.MatchPath(context.Request.Path, endpoint.PathTemplate);
            if (!isMatch || !parameters.TryGetValue("id", out var idStr) || !int.TryParse(idStr, out var id))
            {
                context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                await context.Response.WriteAsync("Invalid test data ID");
                return;
            }

            var testData = await testService.GetTestDataAsync(id);

            context.Response.ContentType = "application/json";
            await context.Response.WriteAsync(JsonSerializer.Serialize(testData, new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                WriteIndented = true
            }));
        }
        catch (ArgumentException ex)
        {
            context.Response.StatusCode = (int)HttpStatusCode.NotFound;
            await context.Response.WriteAsync(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "处理GetTestDataAsync请求失败");
            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            await context.Response.WriteAsync("Failed to get test data");
        }
    }

    /// <summary>
    /// 处理创建测试数据请求
    /// </summary>
    private async Task HandleCreateTestDataAsync(HttpContext context, ITestService testService)
    {
        try
        {
            var name = context.Request.Query["name"].ToString();
            var valueStr = context.Request.Query["value"].ToString();

            if (string.IsNullOrEmpty(name))
            {
                context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                await context.Response.WriteAsync("Name is required");
                return;
            }

            if (!int.TryParse(valueStr, out var value))
            {
                value = 0; // 默认值
            }

            var testData = await testService.CreateTestDataAsync(name, value);

            context.Response.ContentType = "application/json";
            await context.Response.WriteAsync(JsonSerializer.Serialize(testData, new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                WriteIndented = true
            }));
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "处理CreateTestDataAsync请求失败");
            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            await context.Response.WriteAsync("Failed to create test data");
        }
    }

    /// <summary>
    /// 处理获取所有测试数据请求
    /// </summary>
    private async Task HandleGetAllTestDataAsync(HttpContext context, ITestService testService)
    {
        try
        {
            var query = context.Request.Query;
            var page = int.TryParse(query["page"], out var p) ? p : 1;
            var size = int.TryParse(query["size"], out var s) ? s : 10;

            var testDataList = await testService.GetAllTestDataAsync(page, size);

            context.Response.ContentType = "application/json";
            await context.Response.WriteAsync(JsonSerializer.Serialize(new
            {
                data = testDataList,
                page,
                size,
                total = testDataList.Count
            }, new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                WriteIndented = true
            }));
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "处理GetAllTestDataAsync请求失败");
            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            await context.Response.WriteAsync("Failed to get all test data");
        }
    }
}
